<script lang="ts" setup>
import {ref} from "vue"
import {getSearchSuggestListApi, getSuggestListApi} from "@/api/search";
import {debounce} from "@/utils/debounce";
import type {SuggestItem} from "@/types/search";
import {useSearchHistoryStore} from "@/stores/searchHistory";
import {onShow} from "@dcloudio/uni-app";

// 获取顶部安全距离
const {safeAreaInsets} = uni.getSystemInfoSync()
const pageQuery = defineProps<{
  keyword?: string
}>()
const keyword = ref(pageQuery.keyword || '')

uni.$on('goSearch', (data: string) => {
  console.log('goSearch', data)
  keyword.value = data
})

// 搜索
/*搜索历史*/
const searchHistoryStore = useSearchHistoryStore()
// 用户输入框输入
const suggestList = ref<SuggestItem[]>([])
const onInputSearch = debounce(async () => {
  if (!keyword.value) {
    return
  }
  // 这里延迟发送
  const res = await getSuggestListApi(keyword.value)
  res.data.forEach((item: SuggestItem) => {
    item.name = item.name.replace(new RegExp('<em>', 'g'), `<em style="color: #39c5bb;font-style: normal;">`)
  })
  suggestList.value = res.data
}, 200, {leading: true, trailing: false})

//高亮显示——返回数据与关键词对比相同高亮
/**
 *  高亮显示
 * @param keyword 匹配关键词
 * @param data 待匹配数据
 */
const highlight = (keyword: string, data: string) => {
  let regex = new RegExp(keyword, 'gi');
  let match;
  while ((match = regex.exec(data)) !== null) {
    let startIndex = match.index;
    let endIndex = regex.lastIndex;
    let highlightedText = data.substring(startIndex, endIndex);
    let replacement = `<em>${highlightedText}</em>`;
    data = data.substring(0, startIndex) + replacement + data.substring(endIndex);
    regex.lastIndex = startIndex + replacement.length; // 避免死循环
  }
  return data;
}

// 用户搜索框搜索或者点击搜索
const onSearch = () => {
  if (!keyword.value) {
    return
  }
  uni.navigateTo({url: `/subPkg/animalsList/animalsList?keyword=${keyword.value}`})
  // 修改搜索历史
  searchHistoryStore.updateSearchHistory(keyword.value)
  keyword.value = ''
}

/**
 * 用户根据搜索建议搜索
 * @param id 动物id
 * @param name 动物名
 */
const onSearchBySuggest = (id: number | string, name: string) => {
  keyword.value = name.replace(/<[^>]+>/g, '')
  id = id.toString()
  // #ifdef APP-PLUS
  uni.navigateTo({url: '/subPkg/detail/detail?id=' + id})
  // #endif
// #ifndef APP-PLUS
  uni.navigateTo({url: `/subPkg/animalsList/animalsList?keyword=${keyword.value}`})
// #endif
  searchHistoryStore.updateSearchHistory(keyword.value)
  keyword.value = ''
}
/**
 *  用户点击搜索历史搜索
 * @param history
 */
const onSearchByHistory = (history: string) => {
  keyword.value = history
  uni.navigateTo({url: `/subPkg/animalsList/animalsList?keyword=${keyword.value}`})
  searchHistoryStore.updateSearchHistory(keyword.value)
}
//清空历史
const popup = ref()
const onClearHistory = () => {
  if (!searchHistoryStore.searchHistory) {
    return
  }
  //删除前提示
  popup.value.open()
}

//返回
const goBack = () => {
  uni.navigateBack()
}

// 获取推荐热门搜索
const searchSuggestList = ref<SuggestItem[]>()
const getSearchSuggestList = async () => {
  const res = await getSearchSuggestListApi()
  searchSuggestList.value = res.data
}
// onLoad()部分浏览器会有问题
onShow(() => {
  getSearchSuggestList()
})
</script>

<template>
  <view class="search-container">
    <view :style="{ paddingTop: safeAreaInsets?.top! + 20 + 'px', fontSize: '16px' }"
          class="navbar  text-white padding-lr-sm">
      <view class="flex justify-between align-center" style="gap: 20rpx;width: 100%">
        <view class="cuIcon-back flex justify-center align-center " style="width: 44rpx;height: 44rpx;"
              @click="goBack"></view>
        <view class="nav-item" style="flex-grow: 1">
          <input v-model="keyword" :auto-focus="true" :focus="true" placeholder="搜索动物朋友"
                 placeholder-style="color:#999999" style="width: 100%" @confirm="onSearch" @focus="onInputSearch"
                 @input="onInputSearch"/>
        </view>
        <view class="nav-item"
              style="font-size:30rpx;color: #f1f1f1;flex-direction: row;min-width: 60rpx;margin-right: 15px"
              @click="onSearch">
          搜索
        </view>
      </view>
      <!--    渲染搜索建议列表-->
      <view v-if="keyword" :style="{ top: safeAreaInsets?.top! + 65 + 'px' }" class="suggest-list">
        <view v-for="(item, index) in suggestList.slice(0, 10)" :key="index" class="suggest-item"
              @click="onSearchBySuggest(item.id, item.name)">
          <rich-text :nodes="item.name" class="text-gray"></rich-text>
        </view>
      </view>
    </view>
    <!--   搜索历史 -->
    <view v-show="!keyword" class="history" @click="onSearch">
      <view v-show="searchHistoryStore?.searchHistory">
        <view class="history-title">搜索历史
          <uni-icons color="#b9b9b9" size="25" type="trash-filled" @click="onClearHistory"></uni-icons>
        </view>
        <view class="history-list">
          <view v-for="(item, index) in searchHistoryStore.searchHistory?.slice(0, 20)" :key="item" class="history-item"
                @click="onSearchByHistory(item)">{{ item }}
          </view>
        </view>
      </view>
    </view>

    <!--   推荐搜索-->
    <view v-if="!keyword" class="recommend">
      <view class="text-red cuIcon-hot flex padding-left-sm" style="gap: 15rpx;font-size: 32rpx">
        <text class="text-gray">推荐搜索</text>
      </view>
      <view class="recommend-list flex flex-wrap justify-center padding-lg"
            style="width: 100%;gap: 20rpx;column-gap: 40rpx">
        <text v-for="(item,index) in searchSuggestList" :key="index" class="text-black text-lg flex align-center "
              style="min-width: 40%;min-height: 40rpx;padding: 10rpx 10rpx"
              @tap="onSearchBySuggest(item.id,item.name)">{{
            item.name
          }}
        </text>
      </view>

    </view>
  </view>

  <!--  弹出层-->
  <uni-popup ref="popup" type="center">
    <uni-popup-dialog confirm-text="删除全部" content="确定要清空搜索历史吗？" title="提示" type="info"
                      @confirm="searchHistoryStore.clearSearchHistory()">
    </uni-popup-dialog>
  </uni-popup>
</template>

<style lang="scss" scoped>
em { // 只有网页版生效
  color: #39c5bb;
  font-style: normal
}

page {
  background: #FFFFFF;
}


.uni-select__input-placeholder {
  color: #f1f1f1 !important;
}

.search-container {
  width: 100%;

  /* #ifdef H5 */
  background-color: #fff;
  /* #endif */
}

.navbar {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #39c5bb;
  padding-bottom: 10px;

  // 固定
  z-index: 999;
  background-image: url('@/static/circle.png');
  background-size: 80% 200%;
  background-repeat: repeat-x;
  // 右上角
  background-origin: border-box;
  // 背景图片位置
  background-position: left -10px bottom 50px;


  .nav-item {
    display: flex;
    justify-content: center;
    align-items: center;

    image {
      width: 35px;
      height: 35px;
    }

    input {
      border: #3ebed3 1px solid;
      border-radius: 35rpx;
      background-color: rgba(255, 255, 255, 0.3);
      height: 70rpx;
      padding-left: 70rpx;
      color: rgba(255, 255, 255, 0.83);
      background-image: url('@/static/search.png');
      background-repeat: no-repeat;
      background-position: 10px center;
      background-size: 20px;

      &::placeholder {
        color: #fff;
      }
    }
  }

  .img {
    border-radius: 50%;
    border: #3ebed3 1px solid;
    background-color: #3ebed3;
    width: 28px;
    height: 28px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

}

.history {
  display: flex;
  flex-direction: column;
  padding: 10px 10px 0 10px;

  width: 100%;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
    font-size: 32rpx;
    color: #b9b9b9;
    border-bottom: #b9b9b9 1rpx solid;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    .history-item {
      font-size: 14px;
      padding: 10px 15px;
      background-color: rgba(57, 197, 187, 0.75);
      color: #ffffff;
      font-weight: 400;
      margin: 10px;
      border-radius: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      border: none;
    }
  }
}

.suggest-list {
  position: absolute;
  //top: 65px;
  width: 100%;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  z-index: 999;

  .suggest-item {
    border-bottom: #f1f1f1 1px solid;
    display: flex;
    padding: 10px 10px 10px 10px;
  }
}

.recommend {
  width: 100%;
  padding: 30rpx;
}
</style>